import json
import os
from datetime import datetime
from typing import List, Dict
from pathlib import Path

class JavaBugReportGenerator:
    def __init__(self, output_dir: str = "java_bug_reports"):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)
    
    def generate_html_report(self, bug_results: List[Dict], project_path: str) -> str:
        """生成HTML格式的BUG检测报告"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        report_path = self.output_dir / f"java_bug_report_{timestamp}.html"
        
        # 统计信息
        total_files = len(bug_results)
        successful_scans = len([r for r in bug_results if r['status'] == 'success'])
        failed_scans = total_files - successful_scans
        total_tokens = sum(r['tokens_used'] for r in bug_results)
        
        # AI提供商统计
        ai_providers = {}
        for result in bug_results:
            provider = result.get('ai_provider', 'unknown')
            model = result.get('model_name', 'unknown')
            provider_model = f"{provider} ({model})"
            ai_providers[provider_model] = ai_providers.get(provider_model, 0) + 1
        
        # 按严重程度分类
        high_risk = [r for r in bug_results if r.get('severity_level') == 'high']
        medium_risk = [r for r in bug_results if r.get('severity_level') == 'medium']
        low_risk = [r for r in bug_results if r.get('severity_level') == 'low']
        
        # 按包名分组
        packages = {}
        for result in bug_results:
            pkg = result.get('package', 'default')
            if pkg not in packages:
                packages[pkg] = []
            packages[pkg].append(result)
        
        html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Java BUG检测报告</title>
    <style>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }}
        .container {{
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }}
        .header {{
            text-align: center;
            margin-bottom: 40px;
            padding-bottom: 20px;
            border-bottom: 3px solid #667eea;
        }}
        .header h1 {{
            color: #333;
            margin: 0;
            font-size: 2.5em;
        }}
        .ai-info {{
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }}
        .stats {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }}
        .stat-card {{
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 25px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }}
        .stat-card.high-risk {{
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        }}
        .stat-card.medium-risk {{
            background: linear-gradient(135deg, #feca57 0%, #ff9ff3 100%);
        }}
        .stat-card.low-risk {{
            background: linear-gradient(135deg, #48dbfb 0%, #0abde3 100%);
        }}
        .stat-card.kimi {{
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
            color: #333;
        }}
        .stat-number {{
            font-size: 2.5em;
            font-weight: bold;
            margin-bottom: 5px;
        }}
        .severity-overview {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }}
        .severity-card {{
            border: 2px solid;
            border-radius: 10px;
            padding: 20px;
        }}
        .severity-card.high {{
            border-color: #ff6b6b;
            background: #ffe0e0;
        }}
        .severity-card.medium {{
            border-color: #feca57;
            background: #fff8e0;
        }}
        .severity-card.low {{
            border-color: #48dbfb;
            background: #e0f7ff;
        }}
        .file-analysis {{
            margin-bottom: 30px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }}
        .file-header {{
            background: #667eea;
            color: white;
            padding: 20px;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }}
        .file-header.high-risk {{
            background: #ff6b6b;
        }}
        .file-header.medium-risk {{
            background: #feca57;
        }}
        .file-header.low-risk {{
            background: #48dbfb;
        }}
        .file-content {{
            padding: 25px;
            background: white;
        }}
        .model-info {{
            background: #e3f2fd;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            font-size: 0.9em;
            color: #1976d2;
        }}
        .quick-scan {{
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #667eea;
        }}
        .quick-scan h4 {{
            margin-top: 0;
            color: #667eea;
        }}
        .quick-scan ul {{
            margin: 0;
            padding-left: 20px;
        }}
        .error {{
            color: #dc3545;
            background: #f8d7da;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #dc3545;
        }}
        .package-section {{
            margin-bottom: 50px;
        }}
        .package-title {{
            font-size: 1.8em;
            color: #333;
            margin-bottom: 25px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }}
        pre {{
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            overflow-x: auto;
            white-space: pre-wrap;
            border-left: 4px solid #667eea;
        }}
        .timestamp {{
            color: #666;
            font-size: 0.9em;
        }}
        .badge {{
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: bold;
        }}
        .badge.high {{
            background: #ff6b6b;
            color: white;
        }}
        .badge.medium {{
            background: #feca57;
            color: #333;
        }}
        .badge.low {{
            background: #48dbfb;
            color: white;
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🐛 Java BUG检测报告</h1>
            <p class="timestamp">项目路径: {project_path}</p>
            <p class="timestamp">生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
        </div>
        
        <div class="ai-info">
            <h3>🤖 AI模型信息</h3>
            <p>本次检测使用的AI模型分布：</p>
        """
        
        for provider_model, count in ai_providers.items():
            html_content += f"<span style='margin: 0 10px;'>• {provider_model}: {count} 个文件</span>"
        
        html_content += f"""
        </div>
        
        <div class="stats">
            <div class="stat-card">
                <div class="stat-number">{total_files}</div>
                <div>总Java文件数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{successful_scans}</div>
                <div>成功检测</div>
            </div>
            <div class="stat-card high-risk">
                <div class="stat-number">{len(high_risk)}</div>
                <div>高风险文件</div>
            </div>
            <div class="stat-card medium-risk">
                <div class="stat-number">{len(medium_risk)}</div>
                <div>中风险文件</div>
            </div>
            <div class="stat-card low-risk">
                <div class="stat-number">{len(low_risk)}</div>
                <div>低风险文件</div>
            </div>
            <div class="stat-card kimi">
                <div class="stat-number">{total_tokens:,}</div>
                <div>总Token消耗</div>
            </div>
        </div>
        
        <div class="severity-overview">
            <div class="severity-card high">
                <h3>🔴 高风险文件 ({len(high_risk)})</h3>
                <p>这些文件包含可能导致系统崩溃、数据丢失或安全漏洞的严重BUG，需要立即修复。</p>
            </div>
            <div class="severity-card medium">
                <h3>🟡 中风险文件 ({len(medium_risk)})</h3>
                <p>这些文件包含可能影响功能正常运行或性能的重要问题，建议优先修复。</p>
            </div>
            <div class="severity-card low">
                <h3>🟢 低风险文件 ({len(low_risk)})</h3>
                <p>这些文件包含代码质量问题或潜在风险，可以在时间允许时进行改进。</p>
            </div>
        </div>
        
        <div class="detailed-results">
            <h2>📋 详细检测结果</h2>
        """
        
        # 按包名组织结果
        for package_name, package_results in packages.items():
            html_content += f"""
            <div class="package-section">
                <h3 class="package-title">📦 包: {package_name} ({len(package_results)} 个文件)</h3>
            """
            
            # 按严重程度排序
            sorted_results = sorted(package_results, key=lambda x: {
                'high': 0, 'medium': 1, 'low': 2, 'unknown': 3
            }.get(x.get('severity_level', 'unknown'), 3))
            
            for result in sorted_results:
                severity = result.get('severity_level', 'unknown')
                severity_class = severity if severity in ['high', 'medium', 'low'] else 'medium'
                ai_provider = result.get('ai_provider', 'unknown')
                model_name = result.get('model_name', 'unknown')
                
                html_content += f"""
                <div class="file-analysis">
                    <div class="file-header {severity_class}-risk">
                        <div>
                            <span class="badge {severity_class}">{severity.upper()}</span>
                            📄 {result['file_path']}
                        </div>
                        <div>
                            大小: {result['file_size']} bytes | 
                            Token: {result['tokens_used']} |
                            状态: {'✅ 成功' if result['status'] == 'success' else '❌ 失败'}
                        </div>
                    </div>
                    <div class="file-content">
                        <div class="model-info">
                            🤖 分析模型: {ai_provider.upper()} - {model_name}
                        </div>
                """
                
                # 显示快速扫描结果
                if result.get('quick_scan_results'):
                    html_content += """
                        <div class="quick-scan">
                            <h4>🔍 预扫描发现的潜在问题:</h4>
                            <ul>
                    """
                    for issue, count in result['quick_scan_results'].items():
                        html_content += f"<li><strong>{issue}</strong>: {count} 处</li>"
                    html_content += "</ul></div>"
                
                if result['status'] == 'success':
                    html_content += f"<pre>{result['bug_analysis']}</pre>"
                else:
                    html_content += f'<div class="error">{result["bug_analysis"]}</div>'
                
                html_content += """
                    </div>
                </div>
                """
            
            html_content += "</div>"
        
        html_content += """
        </div>
    </div>
</body>
</html>
        """
        
        with open(report_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        return str(report_path)
    
    def generate_summary_report(self, bug_results: List[Dict], project_path: str) -> str:
        """生成简要的Markdown摘要报告"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        report_path = self.output_dir / f"java_bug_summary_{timestamp}.md"
        
        successful_results = [r for r in bug_results if r['status'] == 'success']
        high_risk = [r for r in successful_results if r.get('severity_level') == 'high']
        medium_risk = [r for r in successful_results if r.get('severity_level') == 'medium']
        low_risk = [r for r in successful_results if r.get('severity_level') == 'low']
        
        # AI提供商统计
        ai_providers = {}
        for result in successful_results:
            provider = result.get('ai_provider', 'unknown')
            model = result.get('model_name', 'unknown')
            provider_model = f"{provider} ({model})"
            ai_providers[provider_model] = ai_providers.get(provider_model, 0) + 1
        
        # 统计最常见的问题
        all_quick_scans = {}
        for result in successful_results:
            for issue, count in result.get('quick_scan_results', {}).items():
                all_quick_scans[issue] = all_quick_scans.get(issue, 0) + count
        
        top_issues = sorted(all_quick_scans.items(), key=lambda x: x[1], reverse=True)[:5]
        
        markdown_content = f"""# 🐛 Java BUG检测摘要报告

## 📋 检测概览
- **项目路径**: {project_path}
- **检测时间**: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
- **总文件数**: {len(bug_results)}
- **成功检测**: {len(successful_results)}
- **检测失败**: {len(bug_results) - len(successful_results)}

## 🤖 AI模型使用情况
"""
        
        for provider_model, count in ai_providers.items():
            markdown_content += f"- **{provider_model}**: {count} 个文件\n"
        
        markdown_content += f"""
## 🚨 风险等级分布
- 🔴 **高风险文件**: {len(high_risk)} 个 - 需要立即修复
- 🟡 **中风险文件**: {len(medium_risk)} 个 - 建议优先修复  
- 🟢 **低风险文件**: {len(low_risk)} 个 - 可以逐步改进

## 📊 最常见的潜在问题
"""
        
        for i, (issue, count) in enumerate(top_issues, 1):
            markdown_content += f"{i}. **{issue}**: {count} 处\n"
        
        if high_risk:
            markdown_content += f"""
## 🔴 高风险文件列表
需要立即关注和修复的文件：
"""
            for result in high_risk:
                provider = result.get('ai_provider', 'unknown')
                markdown_content += f"- `{result['file_path']}` (包: {result.get('package', 'default')}) - 分析模型: {provider}\n"
        
        if medium_risk:
            markdown_content += f"""
## 🟡 中风险文件列表  
建议优先修复的文件：
"""
            for result in medium_risk[:10]:  # 只显示前10个
                provider = result.get('ai_provider', 'unknown')
                markdown_content += f"- `{result['file_path']}` (包: {result.get('package', 'default')}) - 分析模型: {provider}\n"
            
            if len(medium_risk) > 10:
                markdown_content += f"- ... 还有 {len(medium_risk) - 10} 个中风险文件\n"
        
        markdown_content += f"""
## 💡 修复建议优先级
1. **立即修复**: 高风险文件中的严重BUG（空指针、资源泄漏、安全漏洞）
2. **优先修复**: 中风险文件中的重要问题（线程安全、性能问题）
3. **逐步改进**: 低风险文件中的代码质量问题

## 📈 统计信息
- **平均每文件Token消耗**: {sum(r['tokens_used'] for r in successful_results) // len(successful_results) if successful_results else 0}
- **总Token消耗**: {sum(r['tokens_used'] for r in bug_results):,}

---
*报告由Java BUG检测智能体自动生成*
*支持OpenAI GPT和Kimi K2模型*
"""
        
        with open(report_path, 'w', encoding='utf-8') as f:
            f.write(markdown_content)
        
        return str(report_path)
